package com.kidback.bbloc259.base;

import com.google.gson.Gson;
import com.kidback.bbloc259.util.GsonUtils;
import com.tencent.mmkv.MMKV;

import java.lang.reflect.Type;

public abstract class BaseProvider<T> {

    protected abstract Type getType();

    protected abstract String getCacheKey();

    protected T t;

    public BaseProvider() {
        if (t == null) {
            String str = MMKV.defaultMMKV().getString(getCacheKey(), null);
            t = GsonUtils.fromJsonStr(str, getType());
        }
    }

    public T get() {
        return t;
    }

    public void put(T value) {
        t = value;
        save();
    }

    public void delete() {
        t = null;
        save();
    }

    public void save() {
        MMKV.defaultMMKV().putString(getCacheKey(), new Gson().toJson(t));
    }

}
